import time
import zipfile
from selenium.webdriver import ChromeOptions
import undetected_chromedriver as uc
def create_proxy_extension(proxy_host, proxy_port, username, password):
    """创建代理认证插件"""
    manifest_json = """
    {
        "version": "1.0.0",
        "manifest_version": 3,
        "name": "Chrome Proxy Auth",
        "background": {
            "service_worker": "background.js"
        },
        "permissions": [
            "proxy",
            "webRequest",
            "webRequestAuthProvider"
        ],
        "host_permissions": [
            "<all_urls>"
        ]
    }
    """

    background_js = f"""
    const config = {{
        mode: "fixed_servers",
        rules: {{
            singleProxy: {{
                scheme: "http",
                host: "{proxy_host}",
                port: {proxy_port}
            }},
            bypassList: ["localhost", "127.0.0.1"]
        }}
    }};

    chrome.proxy.settings.set({{value: config, scope: 'regular'}}, () => {{}});

    chrome.webRequest.onAuthRequired.addListener(
        (details) => {{
            return {{
                authCredentials: {{
                    username: "{username}",
                    password: "{password}"
                }}
            }};
        }},
        {{urls: ["<all_urls>"]}},
        ['blocking']
    );
    """

    # 创建临时插件文件
    plugin_file = 'proxy_auth_plugin.zip'
    with zipfile.ZipFile(plugin_file, 'w') as zp:
        zp.writestr("manifest.json", manifest_json)
        zp.writestr("background.js", background_js)

    return plugin_file


# 代理配置
proxy_host = "58.19.55.9"
proxy_port = 15818
username = "d2231274096"
password = "ela9v3e9"

# 创建Chrome选项
chrome_options = ChromeOptions()
proxy_plugin = create_proxy_extension("180.97.254.78", 26967, username, password)
chrome_options.add_extension(proxy_plugin)
driver_path = r'C:\Program Files\Google\Chrome\Application\chromedriver.exe'
driver = uc.Chrome(driver_executable_path=driver_path,options=chrome_options)
driver.get("http://icanhazip.com/")
time.sleep(10)
print(driver.page_source)
driver.quit()
